from fastapi import APIRouter
from tools.bili_api import get_cookie
import requests

router = APIRouter()

@router.get('/api/bili/check_cookie')
def check_bili_cookie():
    cookie = get_cookie()
    # 检查cookie字段完整性
    if not cookie or not cookie.get('SESSDATA') or not cookie.get('DedeUserID') or not cookie.get('bili_jct'):
        return {"valid": False}
    # 尝试访问B站用户空间页，判断是否登录
    try:
        cookies = {
            'SESSDATA': cookie['SESSDATA'],
            'DedeUserID': cookie['DedeUserID'],
            'bili_jct': cookie['bili_jct']
        }
        headers = {
            'User-Agent': 'Mozilla/5.0',
            'Referer': 'https://www.bilibili.com/'
        }
        resp = requests.get('https://api.bilibili.com/x/web-interface/nav', cookies=cookies, headers=headers, timeout=5)
        data = resp.json()
        # code==0 且有mid字段视为有效
        if data.get('code') == 0 and data.get('data', {}).get('mid'):
            return {"valid": True}
        else:
            return {"valid": False}
    except Exception:
        return {"valid": False}
